﻿using System;
using System.Windows;
using System.Windows.Controls.Theming;

namespace SilverlightControls
{
    public class AppTheme
    {
//        public static void InitTheme(string themeName)
//        {
//            var uri = new Uri(@"XAML/System.Windows.Controls.Theming.ExpressionDark.xaml", UriKind.Relative);
//            ResourceDictionary rd = new ResourceDictionary();
//            rd.Source = uri;
//            Application.Current.Resources.MergedDictionaries.Clear();
//            Application.Current.Resources.MergedDictionaries.Add(rd);
//        }

        public static string GetResourceText(Type type, string empty)
        {
            var rd = new ResourceDictionary();
            string parentNS = type.Assembly.FullName.Split(',')[0];
            string path = empty.Substring(parentNS.Length + 1);
            while (true)
            {
                try
                {
                    string url = string.Format("/{0};component/{1}", parentNS, path);
                    rd.Source = new Uri(url, UriKind.Relative);
                    return url;
                }
                catch
                {
                    int i = path.IndexOf('.');
                    if (i < 0)
                        break;
                    path = path.Remove(i, 1);
                    path = path.Insert(i, "/");
                }
            }
            return String.Empty;
        }

        private static string _curretnTheme = @"/System.Windows.Controls.Theming.ExpressionDark;component/Theme.xaml";//BubbleCreme
        public static string CurretnTheme
        {
            get { return _curretnTheme; }
            set 
            { 
                _curretnTheme = value;
                if (OnThemeChange != null)
                    OnThemeChange(null, EventArgs.Empty);
            }
        }

        internal static event EventHandler OnThemeChange;
    }

    public class DinamicTheme:Theme
    {
        public DinamicTheme()
            : base(new Uri(AppTheme.CurretnTheme, UriKind.Relative))
        {
            base.ThemeUri = new Uri(AppTheme.CurretnTheme, UriKind.Relative);
            SetApplicationThemeUri(Application.Current, ThemeUri);
            AppTheme.OnThemeChange += AppTheme_OnThemeChange;
        }

        //public new Uri ThemeUri { get; set; }
        void AppTheme_OnThemeChange(object sender, EventArgs e)
        {
            ThemeUri = new Uri(AppTheme.CurretnTheme);
        }
    }
}
